package com.likai.jarscms.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UrlValidateInterceptor implements HandlerInterceptor {
	//白名单路径
	private static final String [] IGNORE_URL = {"error","urlError"} ;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		/*//圆括号是正则的特殊字符
        String strKeyWord = "select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|\"\"|or|and|having|\n|\r";
        String strRegex = "[+|-|=|;|/|(|)|[|]|}|{|%|@|*|!|\'|\\]";*/
		
		boolean urlflag = false ;
		//获取请求路径
		String requestPath = request.getServletPath() ;
		for (String path : IGNORE_URL) {
			if(requestPath.contains(path)) {
				urlflag = true ;
				break ;
			}
		}

		if(!urlflag) {
	        boolean flag = true ;
			StringBuffer param = new StringBuffer() ;
			//获得所有请求参数名 
			Enumeration params = request.getParameterNames();
				//遍历参数名
			while(params.hasMoreElements()) {
				param.setLength(0);
				//取得参数名
				String name = params.nextElement().toString() ;
				//取得对应的参数值
				String [] values = request.getParameterValues(name) ;
				for(int i = 0 ; i < values.length ; i ++) {
					param.append(values[i]) ;
				}

				if(sqlValidate(param.toString())) {
					flag = true ;
				} else {
					flag = false ;
					break;
				}
			}

			if(flag) {
				return true;
			} else {
				request.getRequestDispatcher("/urlError").forward(request, response) ;
				return false;
			}
		}else {
			return true ;
		}

		
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	//效验  
    protected boolean sqlValidate(String str) {  
        str = str.toLowerCase();//统一转为小写  
        //guid判断
        String strGuidRegex = "[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}";
        String strDateregex = "((\\d{2}(([02468][048])|([13579][26]))[\\-]((((0?[13578])|(1[02]))[\\-]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-]((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-]((((0?[13578])|(1[02]))[\\-]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-]((0?[1-9])|(1[0-9])|(2[0-8]))))))";
        
        //过滤掉的sql关键字，可以手动添加  
        String badStr = "'|and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|" +  
                "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +  
                "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#|\\n|\\r";
        if(str.matches(strDateregex) || str.matches(strGuidRegex)) {
        	return true ;
        } else {
        	boolean flag = false ; 
        	String[] badStrs = badStr.split("[|]");  
            for (int i = 0; i < badStrs.length; i++) {  
                if (str.indexOf(badStrs[i]) !=-1) {  
                     
                    flag = false ;
                	break ;
                } else {
                	flag = true ; 
                }
            }
            
            if(flag) {
            	return true ;
            } else {
            	return false ;
            }
        }
    } 
	
}
